/*
	The MIT License

	Copyright (c) 2010 IFMO/GameDev Studio

	Permission is hereby granted, free of charge, to any person obtaining a copy
	of this software and associated documentation files (the "Software"), to deal
	in the Software without restriction, including without limitation the rights
	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
	copies of the Software, and to permit persons to whom the Software is
	furnished to do so, subject to the following conditions:

	The above copyright notice and this permission notice shall be included in
	all copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
	THE SOFTWARE.
*/

#include "d3d_local.h"


/*-----------------------------------------------------------------------------
	D3D Model :	
-----------------------------------------------------------------------------*/

struct vertex_s {
		EVec3   pos;
		EVec3   normal;
		EVec3   tangent;
		EVec3   binormal;
		EVec2   uv;
		EVec4	color;
		EVec4	weights;
		EVec4	joint_inds;
	};



const D3DVERTEXELEMENT9 VERTEX_DECL_STATIC[] = {
		{ 0, offsetof(vertex_s, pos			), D3DDECLTYPE_FLOAT3,	D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION,	0 },
		{ 0, offsetof(vertex_s, normal		), D3DDECLTYPE_FLOAT3,	D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_NORMAL,		0 },
		{ 0, offsetof(vertex_s, tangent		), D3DDECLTYPE_FLOAT3,	D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TANGENT,    0 },
		{ 0, offsetof(vertex_s, binormal	), D3DDECLTYPE_FLOAT3,	D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_BINORMAL,   0 },
		{ 0, offsetof(vertex_s, uv			), D3DDECLTYPE_FLOAT2,	D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD,   0 },
		{ 0, offsetof(vertex_s, color		), D3DDECLTYPE_FLOAT4,	D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_COLOR,		0 },
		{ 0, offsetof(vertex_s, weights     ), D3DDECLTYPE_FLOAT4,  D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_BLENDWEIGHT,   0 },
		{ 0, offsetof(vertex_s, joint_inds  ), D3DDECLTYPE_FLOAT4,  D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_BLENDINDICES,   0 },
		D3DDECL_END()
	};


//
//	ED3DMesh::ED3DMesh
//
ED3DMesh::ED3DMesh( ERSMeshSystem *mss, ED3DRenderSystem *rs )
{
	this->mss	=	mss;
	this->rs	=	rs;
	d3ddev		=	rs->GetDevice();
	
	decl		=	NULL;
	ib			=	NULL;
	vb			=	NULL;
	
	num_tris	=	0;
	num_verts	=	0;
}


//
//	ED3DMesh::~ED3DMesh
//
ED3DMesh::~ED3DMesh( void )
{
	ReleaseModel();
}


/*-----------------------------------------------------------------------------
	D3D Model :	
-----------------------------------------------------------------------------*/

//
//	ED3DMesh::ReleaseModel
//
void ED3DMesh::ReleaseModel( void )
{
	SAFE_RELEASE( decl );
	SAFE_RELEASE( ib );
	SAFE_RELEASE( vb );
}


//
//	ED3DMesh::UpdateFromMesh
//
void ED3DMesh::UpdateFromMesh( const IPxTriMesh input_mesh )
{
	IPxTriMesh	mesh	=	input_mesh;

	uint format		=	mesh->GetFormat();
	uint usage		=	D3DUSAGE_DYNAMIC | D3DUSAGE_WRITEONLY;
	D3DPOOL pool	=	D3DPOOL_DEFAULT;
	
	num_tris		=	mesh->GetTriangleNum();
	num_inds		=	mesh->GetTriangleNum() * 3;
	num_verts		=	mesh->GetVertexNum();
	
	ASSERT( format & GE_MESH_POSITION );
	
	uint	vb_len	=	num_verts * sizeof(vertex_s);
	uint	ib_len	=	num_inds * sizeof(uint);
	
	bool has_tangents	= 0!=(format & GE_MESH_TANGENT);
	bool has_binormals	= 0!=(format & GE_MESH_BINORMAL);

	//
	//	Compute tangent space if necessary :
	//		
	if (!has_tangents || !has_binormals) {
		mesh = mesh->Clone();
		mesh->SetFormat( format | GE_MESH_TANGENT | GE_MESH_BINORMAL );
		mesh->ComputeTangents();
	}

	//
	//	create vertex and index buffers :	
	//
	SAFE_RELEASE( decl );
	SAFE_RELEASE( ib );
	SAFE_RELEASE( vb );
	if (vb_len==0 || ib_len==0) {
		return;
	}
	HRCALL( d3ddev->CreateVertexBuffer( vb_len, usage, 0, pool, &vb, NULL) );
	HRCALL( d3ddev->CreateIndexBuffer ( ib_len, usage, D3DFMT_INDEX32, pool, &ib, NULL) );
	HRCALL( d3ddev->CreateVertexDeclaration( VERTEX_DECL_STATIC, &decl ) );


	uint	 *ib_ptr	= NULL;
	vertex_s *vb_ptr	= NULL;

	//
	//	write vertices :	
	//
	HRCALL( vb->Lock(0, 0, (void**)(&vb_ptr), 0) );
	
	for (uint i=0; i<num_verts; i++) {
		EVertex	v = mesh->GetVertex(i);
		
		vb_ptr[i].pos		=	v.position;
		vb_ptr[i].normal	=	v.normal;
		vb_ptr[i].binormal	=	v.binormal;
		vb_ptr[i].tangent	=	v.tangent;
		//vb_ptr[i].color		=	v.color0; !!!!!!!!!!!!!!!!!!!!!!!!
		
		vb_ptr[i].color		=	EVec4(1,1,1,1);
		vb_ptr[i].uv		=	v.uv0;
		vb_ptr[i].weights	=	EVec4(v.joint_weights[0], v.joint_weights[1], v.joint_weights[2], v.joint_weights[3]);
		vb_ptr[i].joint_inds=	EVec4(v.joint_inds[0],	  v.joint_inds[1],    v.joint_inds[2],    v.joint_inds[3]);
	}
	
	HRCALL( vb->Unlock() );

	//	
	//	write indices :
	//
	HRCALL( ib->Lock(0, 0, (void**)(&ib_ptr), 0) );
	
	for (uint i=0; i<mesh->GetTriangleNum(); i++) {
		uint i0, i1, i2;
		mesh->GetTriangle(i, i0, i1, i2);

		ib_ptr[i*3+0] = i0;
		ib_ptr[i*3+1] = i1;
		ib_ptr[i*3+2] = i2;
	}
	
	HRCALL( ib->Unlock() );
}


//
//	ED3DMesh::DrawAllSubsets
//
void ED3DMesh::DrawAllTris( void ) const
{
	if (!decl || !vb || !ib) {
		return;
	}

	HRCALL( d3ddev->SetVertexDeclaration( decl ) );

	HRCALL( d3ddev->SetStreamSource(0, vb,  0, sizeof(vertex_s)) );
	HRCALL( d3ddev->SetIndices( ib ) );
	
	HRCALL( d3ddev->DrawIndexedPrimitive( D3DPT_TRIANGLELIST, 0, 0, num_verts, 0, num_tris) );
}


//
//	ED3DMesh::DrawSubset
//
void ED3DMesh::DrawTris( uint start_tri, uint num_tris_to_draw ) const
{
	if (!decl || !vb || !ib) {
		return;
	}

	ASSERT(start_tri + num_tris_to_draw <= num_tris);

	HRCALL( d3ddev->SetVertexDeclaration( decl ) );

	HRCALL( d3ddev->SetStreamSource(0, vb,  0, sizeof(vertex_s)) );
	HRCALL( d3ddev->SetIndices( ib ) );
	
	HRCALL( d3ddev->DrawIndexedPrimitive( D3DPT_TRIANGLELIST, 0, 0, num_verts, start_tri * 3, num_tris_to_draw) );
}

